package net.csdn.business.notify.handler.action;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.notify.common.constant.CommonConstants;
import net.csdn.business.notify.common.model.dto.UserFansCheckDTO;
import net.csdn.business.notify.common.model.query.NotifyUserSettingQuery;
import net.csdn.business.notify.common.model.vo.NotifyUserSettingVO;
import net.csdn.business.notify.common.pipeline.BusinessProcess;
import net.csdn.business.notify.common.pipeline.ProcessContext;
import net.csdn.business.notify.common.pipeline.domain.PrivateTaskInfo;
import net.csdn.business.notify.feign.SystemFeignClient;
import net.csdn.business.notify.handler.service.INotifyUserSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * @ClassName PrivateShieldAction
 * @Description 根据用户关注关系，是否屏蔽私信
 * @Author zhangyl
 * @Date 2023/12/5 18:16
 */
@Slf4j
@Service
public class PrivateShieldAction implements BusinessProcess<PrivateTaskInfo> {


    @Autowired
    private SystemFeignClient systemFeignClient;
    @Autowired
    private INotifyUserSettingService userSettingService;

    @Override
    public void process(ProcessContext<PrivateTaskInfo> context) {
        PrivateTaskInfo taskInfo = context.getProcessModel();
        String senderId=taskInfo.getSenderId();
        List<String> receiversBefore=new ArrayList<>(taskInfo.getReceiver());
        //查询系统预设配置,如果系统预设都没这个配置，证明这个配置用户也不可能存在，直接跳过。
        NotifyUserSettingVO systemSet=userSettingService.selectNotifyUserSetting(CommonConstants.USER_TARGET_TYPE,CommonConstants.USER_MESSAGE_ACT,"-1");
        if (systemSet!=null) {
            //获取用户配置
            //防止查询数据过多，分批查询
            Set<String> receiversAfter = new HashSet<>();
            List<List<String>> uidBathList = Lists.partition(receiversBefore, 200);
            for (List<String> userIdList : uidBathList) {
                //批量查询用户信息配置信息
                List<String> batchUserIdAfter = new ArrayList<>();
                NotifyUserSettingQuery query = new NotifyUserSettingQuery();
                query.setAct(CommonConstants.USER_MESSAGE_ACT);
                query.setTargetType(CommonConstants.USER_TARGET_TYPE);
                query.setUserIds(userIdList);
                List<NotifyUserSettingVO> userSetting = userSettingService.batchQuery(query);
                if (userSetting != null && userSetting.size() > 0) {
                    userSetting.forEach(setting -> {
                        boolean result=false;
                        String userId = setting.getUserId();
                        JSONObject set = setting.getSetting();
                        if (set != null) {
                            for (Integer i=30;i>=10;){
                                String key=i.toString();
                                JSONObject channelSet=set.getJSONObject(key);
                                Boolean isOpen=channelSet.getBoolean(CommonConstants.IS_OPEN);
                                if(isOpen){
                                    try {
                                        UserFansCheckDTO checkParams=new UserFansCheckDTO();
                                        switch (key){
                                            case CommonConstants.USER_MESSAGE_10:
                                                //查询当前用户是否是接收用户的已关注的人
                                                checkParams.setFrUserId(userId);
                                                checkParams.setToUserId(senderId);
                                                Boolean isFans=systemFeignClient.fansCheck(checkParams);
                                                if(isFans){
                                                    result=true;
                                                }
                                                break;
                                            case CommonConstants.USER_MESSAGE_20:
                                                //查询当前用户是否关注接收用户
                                                checkParams.setFrUserId(senderId);
                                                checkParams.setToUserId(userId);
                                                Boolean isFollows=systemFeignClient.fansCheck(checkParams);
                                                if(isFollows){
                                                    result=true;
                                                }
                                                break;
                                            case CommonConstants.USER_MESSAGE_30:
                                                result=true;
                                                break;
                                        }
                                    }catch (Exception e){
                                        result=false;
                                        e.printStackTrace();
                                        log.error("userSendPrivateEnable user fans check error!");
                                    }
                                }
                                if(result){
                                    //只要有一个为真，则终止返回结果
                                    batchUserIdAfter.add(userId);
                                    break;
                                }
                                i=i-10;
                            }
                            //用户设置的 所有人、关注我的人、我关注的人三种关系都不通过，则打印日志
                            if(!result){
                                log.info("notify shield by user setting:target_type:{},act:{},user：{}, ", CommonConstants.USER_TARGET_TYPE, CommonConstants.USER_MESSAGE_ACT, userId);
                            }
                            userIdList.remove(userId);
                        }
                    });
                }
                //用户自定义配置验证完毕之后，判断userIdList是否为空，不为空，证明还剩余用户走的是默认系统配置。
                if (userIdList.size() > 0) {
                    userIdList.forEach(userId -> {
                        boolean result=false;
                        JSONObject set = systemSet.getSetting();
                        if (set != null) {
                            for (Integer i=30;i>=10;){
                                String key=i.toString();
                                JSONObject channelSet=set.getJSONObject(key);
                                Boolean isOpen=channelSet.getBoolean(CommonConstants.IS_OPEN);
                                if(isOpen){
                                    try {
                                        UserFansCheckDTO checkParams=new UserFansCheckDTO();
                                        switch (key){
                                            case CommonConstants.USER_MESSAGE_10:
                                                //查询当前用户是否是接收用户的已关注的人
                                                checkParams.setFrUserId(userId);
                                                checkParams.setToUserId(senderId);
                                                Boolean isFans=systemFeignClient.fansCheck(checkParams);
                                                if(isFans){
                                                    result=true;
                                                }
                                                break;
                                            case CommonConstants.USER_MESSAGE_20:
                                                //查询当前用户是否关注接收用户
                                                checkParams.setFrUserId(senderId);
                                                checkParams.setToUserId(userId);
                                                Boolean isFollows=systemFeignClient.fansCheck(checkParams);
                                                if(isFollows){
                                                    result=true;
                                                }
                                                break;
                                            case CommonConstants.USER_MESSAGE_30:
                                                result=true;
                                                break;
                                        }
                                    }catch (Exception e){
                                        result=false;
                                        e.printStackTrace();
                                        log.error("userSendPrivateEnable user fans check error!");
                                    }
                                }
                                if(result){
                                    //只要有一个为真，则终止返回结果
                                    batchUserIdAfter.add(userId);
                                    break;
                                }
                                i=i-10;
                            }
                            //用户设置的 所有人、关注我的人、我关注的人三种关系都不通过，则打印日志
                            if(!result){
                                log.info("notify shield by user setting:target_type:{},act:{},user：{}, ", CommonConstants.USER_TARGET_TYPE, CommonConstants.USER_MESSAGE_ACT, userId);
                            }
                        }
                    });
                }
                receiversAfter.addAll(batchUserIdAfter);
                if(uidBathList.size()==0){
                    break;
                }
            }
            taskInfo.setReceiver(receiversAfter);
        }
    }
}
